<script setup lang="ts">
import {inject, onMounted, ref, watch} from "vue";
import type {UploadChangeParam} from 'ant-design-vue';
import {message} from "ant-design-vue";
import {BASE_URL} from "@/api/config";
import api from "@/api";
import {useRouter} from "vue-router";

//头像逻辑
//用户数据
const userInfo = inject("userInfo")
//上传事件
const handleChange = (info: UploadChangeParam) => {
  if (info.file.status !== 'uploading') {
    message.info('上传中')
  }
  if (info.file.status === 'done') {
    message.success('上传成功')
    getAvatar()
  } else if (info.file.status === 'error') {
    message.error(`${info.file.name} 上传失败`);
    getAvatar()
  }
};
// 上传时的请求头
const headers = {
  "Authorization": sessionStorage.getItem("token")
}
//头像URL
const avatarUrl = ref('')
//请求头像
const getAvatar = async () => {
  const res = await api.getFile({uuid: userInfo.value.avatar})
  avatarUrl.value = BASE_URL + res.data.data.path
}

//表单逻辑
//用户表单
const profileForm = ref({})

//检测userInfo修改用户表单
watch(() => userInfo.value, (newVal) => {
  if (newVal) {
    profileForm.value = {...newVal}
  }
}, {deep: true, immediate: true})

//获取账户名称
const accountName = ref()
const getAccountName = async () => {
  const res = await api.getAccount()
  accountName.value = res.data.data
}

const updateUserInfo: Function | undefined = inject('updateUserInfo')
//用户资料更新
const update = () => {
  api.updateUser({nickname: profileForm.value.nickname, signature: profileForm.value.signature}).then(res => {
    message.success("修改资料成功")
    updateUserInfo && updateUserInfo()
  })
}

//密码修改框的显示逻辑
const pwdEditModalVisible = ref(false)
const showPwdEditModal = () => {
  pwdEditModalVisible.value = true
}

// 密码修改业务逻辑
//表单数据
const pwdEditForm = ref({newPassword: null, confirmPassword: null})
//表单校验规则
const formRules = {
  newPassword: [{required: true, message: '新密码不符合规范', max: 14, min: 8, trigger: 'blur', whitespace: true}],
  confirmPassword: [{
    required: true,
    message: '确认密码不符合规范',
    max: 14,
    min: 8,
    trigger: 'blur',
    whitespace: true
  }, {
    message: '两次密码输入不一致', trigger: 'blur', whitespace: true, validator: (rule, value, callback) =>
        value === pwdEditForm.value.newPassword ? callback() : callback(false)
  }]
}

const router = useRouter()
const formRef = ref(null)
const handleOk = () => {
  formRef.value && formRef.value.validate().then(() => {
    api.updatePassword({
      newPassword: pwdEditForm.value.newPassword,
      confirmPassword: pwdEditForm.value.confirmPassword
    }).then(res => {
      message.success('密码修改成功')
      sessionStorage.clear()
      router.replace('/login')
      pwdEditForm.value = {newPassword: null, confirmPassword: null}
    })
  }).catch(err => {
    console.log(err)
  })
}

const handelCancel = () => {
  pwdEditForm.value = {newPassword: null, confirmPassword: null}
}

onMounted(() => {
  getAvatar()
  getAccountName()
})
</script>
<template>
  <div class="setting-board">
    <div class="setting-control">
      <a-button type="primary" class="control-btn" @click="update">应用</a-button>
    </div>
    <div class="setting-item">
      <div class="setting-item-container">
        <a-avatar :size="50" class="avatar" :src="avatarUrl">
          <span class="text">{{ userInfo.nickname.substring(0, 1) }}</span>
        </a-avatar>
        <a-upload
            name="files"
            action="/api/upload/add"
            :headers="headers"
            :data="{useType:'avatar'}"
            @change="handleChange"
            :showUploadList="false"
        >
          <a-button style="color: #413E4A">
            上传头像
          </a-button>
        </a-upload>
      </div>
    </div>


    <div class="setting-item">
      <div class="setting-item-container">
        <div class="left-label">账户</div>
        <div class="right-input">
          <input v-model="accountName" disabled style="color: #78738A"/>
        </div>
      </div>
      <div class="setting-item-container">
        <div class="left-label">密码</div>
        <div class="right-input" @click="showPwdEditModal">
          <span style="cursor:pointer;">*******</span>
        </div>
      </div>
      <div class="divider-container">
        <a-divider class="divider"></a-divider>
      </div>
      <div class="setting-item-container">
        <div class="left-label">昵称</div>
        <div class="right-input">
          <input v-model="profileForm.nickname"/>
        </div>
      </div>
      <div class="divider-container">
        <a-divider class="divider"></a-divider>
      </div>
      <div class="setting-item-container">
        <div class="left-label">个人介绍</div>
        <div class="right-input">
          <input v-model="profileForm.signature"/>
        </div>
      </div>
    </div>
    <a-modal v-model:visible="pwdEditModalVisible" title="密码修改" @ok="handleOk" :closable="false" :keyboard="false"
             :maskClosable="false" okText="确认修改" cancel-text="取消" :destroyOnClose="true" @cancel="handelCancel">
      <a-form :model="pwdEditForm" :label-col="{ span: 8 }"
              style="width: 400px;margin: 0 auto"
              labelAlign="left"
              :rules="formRules"
              ref="formRef"
              :wrapper-col="{ span: 16 }">
        <a-form-item
            label="新密码"
            name="newPassword"
        >
          <a-input type="password" v-model:value="pwdEditForm.newPassword"></a-input>
        </a-form-item>
        <a-form-item
            label="确认密码"
            name="confirmPassword"
        >
          <a-input type="password" v-model:value="pwdEditForm.confirmPassword"></a-input>
        </a-form-item>
      </a-form>

    </a-modal>

  </div>
</template>
<style lang="less" scoped>
.setting-board {
  height: calc(100% - 40px);
  position: relative;

  .setting-control {
    position: absolute;
    bottom: -40px;
    width: 100%;
    height: 40px;
    display: flex;
    justify-content: flex-end;
    padding: 0 10px;
    align-items: center;

    .control-btn {
      width: 70px;
      height: 30px;
    }
  }

  .setting-item {
    width: 100%;
    background-color: #F2F2F2;
    border-radius: 6px;
    margin-top: 8px;

    .setting-item-container {
      //margin-top: 3px;
      display: flex;
      align-items: center;
      padding: 10px 20px;
      justify-content: space-between;

      .left-label {
        display: flex;

        .setting-title {
          user-select: none;
        }
      }

      .right-input {
        input {
          outline: none;
          width: 150px;
          border: none;
          height: 30px;
          background-color: #F2F2F2;
          text-align: right;
          font-weight: 500;
        }
      }

      .avatar {
        background-color: #2D82E0;

        .text {
          font-size: 20px;
        }
      }

      .upload-btn {
        border-radius: 5px;
        color: #3E3C47;
        font-weight: 500;
      }
    }

    .divider-container {
      padding: 0 10px;

      .divider {
        margin: 0;
        padding: 0;
      }
    }


  }
}
</style>
